import { login, logout, getInfo } from '@/api/user'
import { setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import { getToken } from '@/api/user'
import { Message } from 'element-ui'
const getDefaultState = () => {
  return {
    token: '',
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // get token
  GET_TOKEN({ commit }) {
    const params = {}
    return new Promise((resolve, reject) => {
      getToken(params).then(response => {
        if (response.code === 0) {
          setToken(response.data.randomNumber)
          commit('SET_TOKEN', response.data.randomNumber)
          resolve()
        } else {
          Message({
            type: 'error',
            message: response.message
          })
        }
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user login
  login({ commit }, params) {
    return new Promise((resolve, reject) => {
      login(params).then(response => {
        // const { data } = response
        if (response.code === 0) {
          // commit('SET_TOKEN', response.data.token)
          // commit('SET_NAME', response.userName)
          setToken(response.randomNumber)
          resolve(response)
        } else {
          Message({
            type: 'error',
            message: response.message
          })
          resolve(response)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        if (response.code === 0) {
          const data = response.data
          window.sessionStorage.setItem('hsa-portal-user', JSON.stringify(data))
          commit('SET_NAME', data)
          resolve(response)
        } else {
          reject(response.message)
        }
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        window.sessionStorage.removeItem('hsa-portal-user')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

